package com.spatio.serving.basic.service.template.server.controller;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.spatio.serving.basic.service.template.common.domain.MealDo;
import com.spatio.serving.basic.service.template.common.domain.HistoryCaloriesDo;
import com.spatio.serving.basic.service.template.common.domain.mutliFoodRecordDo;
import com.spatio.serving.basic.service.template.core.component.service.MealService;
import com.spatio.serving.basic.service.template.mysql.Result.Result;
import com.spatio.serving.basic.service.template.server.Interceptor.JWTInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigInteger;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/api/v1/meal")
public class MealController {


    @Autowired
    private MealService mealService;

    //查询用户某一日期所有的营养数据

    @GetMapping("/query_meal")
    public Result meal_query() {
        //@RequestBody UserDo user ,LocalDateTime time){
        Integer user_id = 1;
        LocalDate time = LocalDate.now();
        List<MealDo> res = mealService.queryBydate(user_id, time);
        return Result.success(res);
    }

    /**
     * 根据date查询用户总的营养数据
     * @param date
     * @return
     */

    @GetMapping("/history_query")
    public Result history_query(@RequestParam("date") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate date) {
        //@RequestBody UserDo user ,LocalDateTime time){
        BigInteger user_id = JWTInterceptor.getUserInfo().getUser_id();
        HistoryCaloriesDo res = mealService.queryHistory(user_id, date);
        return Result.success(res);

    }

    /**
     * 根据date和kind查询用户记录的食物
     * @param date
     * @param kind
     * @return
     */
    @GetMapping("/kind_query")
    public Result queryByKind(@RequestParam("date") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate date
                             ,@RequestParam String kind) {
        //@RequestBody UserDo user ,LocalDateTime time){
        BigInteger user_id = JWTInterceptor.getUserInfo().getUser_id();
        HistoryCaloriesDo res = mealService.queryByKind(user_id, date,kind);
        return Result.success(res);

    }

    //没用
    @PostMapping("/update_meal")
    public Result record(@RequestBody MealDo meal) {
        meal.setDateTime(LocalDateTime.now());
        boolean flag = mealService.update_meal(meal);
        return Result.success(flag);

    }

    /**
     * 根据 message_id 获得生成的json记录 ，根据conversation_id获得用户本次对话传入的图片url
     * @param message_id
     * @param conversation_id
     * @return
     */
    @GetMapping("food_log")
    //用户生成记录
    public Result meal_record(@RequestParam String message_id, @RequestParam String conversation_id) {
        BigInteger user_id = JWTInterceptor.getUserInfo().getUser_id();
        List<String> imageUrl = mealService.queryUrlLog(user_id, conversation_id);
        JSONObject finalRes = new JSONObject();
        JSONArray foodLog = mealService.queryFoodLog(user_id, message_id);
        finalRes.put("food", foodLog);
        if (imageUrl.get(0) != null) {
            finalRes.put("url", imageUrl);
        }
        return Result.success(finalRes);

    }

    /**
     * 用户确认完成记录
     * @param completeFood
     * @return
     * @throws IOException
     */

    @PostMapping("complete_record")
    public Result complete_reord(@RequestBody JSONObject completeFood) throws IOException {
        BigInteger user_id = JWTInterceptor.getUserInfo().getUser_id();
//        try {
//            boolean flag = mealService.completeRecord(user_id,completeFood);
//            if(flag){
//                return Result.success(flag);
//            }
//            return Result.error("记录失败");
//        } catch (Exception e) {
//            return Result.error(e.toString());
//        }

        boolean flag = mealService.completeRecord(user_id,completeFood);
        if(flag){return Result.success(flag);}
        return Result.error("记录失败");

    }

    /**
     * 根据传入的类型（历史、主页、记录）推荐食物
     * @param recommendParams
     * @param res
     * @throws IOException
     */
    @PostMapping("recommend_food")
    public void recommend_food(@RequestBody JSONObject recommendParams, HttpServletResponse res) throws IOException {
        res.setContentType("text/event-stream;charset=UTF-8");
        res.setHeader("Cache-Control", "no-cache");
        res.setHeader("Connection", "keep-alive");
        BigInteger user_id = JWTInterceptor.getUserInfo().getUser_id();
        mealService.recommendFood(user_id, recommendParams, res);
    }

    /**
     * 根据uuid删除单个食物
     * @param uuidJson
     * @return
     */
    @PostMapping("delete_food")
    public Result delete_food(@RequestBody JSONObject uuidJson) {
        BigInteger user_id = JWTInterceptor.getUserInfo().getUser_id();
        String uuid = uuidJson.getString("uuid");
        boolean flag = mealService.deleteFood(user_id, uuid);
        if (flag) {
            return Result.success(flag);
        } else {
            return Result.error("删除失败");
        }

    }

    /**
     * 根据uuid修改食物信息
     * @param changedFood
     * @return
     */
    @PostMapping("change_food")
    public Result change_food(@RequestBody JSONObject changedFood) {
        BigInteger user_id = JWTInterceptor.getUserInfo().getUser_id();
        boolean flag = mealService.changeFood(user_id, changedFood);
        JSONObject res= new JSONObject();
        res.put("state", flag);
        if (flag) {
            return Result.success(res);
        } else {
            return Result.error(res);
        }
    }
}